from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.constants import EXPIRES_IN
from users.models import User
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer, BadData


def jwt_response_payload_handler(token, user=None, request=None):
    """
    改写obtain_jwt_token方法里面的response自定义登录视图jwt认证成功返回数据
    """
    return {
        'user_id':user.id,
        'username':user.username,
        'token': token
    }


# 自定义一个django的认证后端类继承ModelBackend
class UsernameMobileAuthBackend(ModelBackend):
    # 重写authenticate方法,
    def authenticate(self, request, username=None, password=None, **kwargs):

        try:  # 用户名或者手机号,只要其中一项查到用户,就让其登录,
            # 但是可能会存在一个小问题:一个人的用户名恰巧是另一个人的手机号,可能会出现混乱,所以再创建用户的时候正则规定以字母开头
            user = User.objects.get(Q(username=username)|Q(mobile=username))
        except User.DoesNotExist:
            return None

        if user.check_password(password) and self.user_can_authenticate(user):
            return user

def generate_find_password_accesstoken(mobile):
    """
    使用itsdangerous模块，生成加密后的access_token
    """

    secret_key = settings.SECRET_KEY

    serializer = TJWSSerializer(secret_key, EXPIRES_IN) # 加密的有效时间60*10

    access_token = serializer.dumps({'mobile': mobile})

    return access_token.decode()


def decode_accesstoken(req_data):
    """解密access_token"""
    secret_key = settings.SECRET_KEY

    serializer = TJWSSerializer(secret_key)

    try:
        res_dict = serializer.loads(req_data)
    except BadData:
        return None

    return res_dict